import { FC, useEffect } from "react";
import style from "./index.module.scss";
import { RollbackOutlined, SaveOutlined } from "@ant-design/icons";
import QuickButtons from "./QuickButtons";
import classnames from "classnames/bind";
import { Button, Space, Typography, message } from "antd";
import { saveQuestion,publishQuestion } from "../../service";
import { useRequest, useDebounceFn,useKeyPress } from "ahooks";
import { useNavigate, useParams } from "react-router-dom";
import useGetPageInfo from "../../hooks/useGetPageInfo";
import useGetQuestion from "../../hooks/useGetQuestion";
const CBN = classnames.bind(style);
const { Title } = Typography;
const HeadPanel: FC = () => {
  let pageInfo = useGetPageInfo();
  const { componentList } = useGetQuestion();
  const nav = useNavigate();
  const {id = ''} = useParams()
  const { run: savequestion, loading } = useRequest(
    () => {
      return saveQuestion({ ...pageInfo, componentList });
    },
    {
      manual: true,
    }
  );

  const { run: savePagedebounce } = useDebounceFn(
    () => {
      savequestion();
    },
    {
      wait: 500,
    }
  );

  const {run:PublishQuestion,loading:PublishQuestion_loading} = useRequest(()=>{
    return publishQuestion(id)
  },{
    manual:true,
    onSuccess(){
      nav({
        pathname:`/question/stat/${id}`,
      })
      message.success('发布成功')
    }
  })

  useKeyPress(['ctrl.s'], (e:KeyboardEvent) => {
    e.preventDefault();
    if(loading) return 
    savequestion();
  });


  useEffect(() => {
    savePagedebounce();
  }, [componentList,pageInfo]);

  return (
    <div className={CBN("HeadContainer")}>
      <Space>
        <Button
          icon={<RollbackOutlined />}
          type="link"
          onClick={() => {
            nav(-1);
          }}
        >
          {" "}
          返回{" "}
        </Button>
        <Title level={3} style={{ margin: 0 }}>
          {pageInfo.title}
        </Title>
      </Space>
      <div className={CBN("quickBox")}>
        <QuickButtons></QuickButtons>
      </div>
      <Space>
        <Button
          icon={<SaveOutlined />}
          disabled={loading}
          loading={loading}
          type="primary"
          onClick={() => {
            savequestion();
          }}
        >
          {" "}
          保存{" "}
        </Button>
        <Button icon={<SaveOutlined />} type="default" onClick={PublishQuestion} loading = {PublishQuestion_loading} disabled = {PublishQuestion_loading}>
          {" "}
          发布{" "}
        </Button>
      </Space>
    </div>
  );
};

export default HeadPanel;
